//
// Created on 2025/7/23.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#ifndef STREAMCORE_FILE_STREAM_H
#define STREAMCORE_FILE_STREAM_H

#include "safe_file_handle.h"
#include "stream.h"


class FileStream : Stream {
public:
    FileStream(std::string path, FileMode mode, FileAccess access = FileAccess::ReadWrite,
               FileShare share = FileShare::None, size_t bufsize = 4096);

    ~FileStream() = default;

    // 禁止拷贝
    FileStream(const FileStream &) = delete;
    FileStream &operator=(const FileStream &) = delete;

    bool canRead() const noexcept override;
    bool canWrite() const noexcept override;
    bool canSeek() const noexcept override;

    size_t position() const override;
    size_t length() const override;
    void setLength(size_t length) override;

    long read(void *buf, long offset, size_t len) override;
    void write(const void *buf, long offset, size_t len) override;
    size_t seek(long offset, SeekOrigin origin) override;
    void flush() override;

protected:
    void onClose() override;

private:
    void purgeBeforeWrite();
    void flushReadBuffer();
    void flushWriteBuffer();

    void writeToBuffer(const void *data, size_t size);

    std::unique_ptr<SafeFileHandle> handle_;

    std::unique_ptr<char[]> buff_;
    size_t bufsize_;

    size_t write_buffer_count_; // 表示实际写入缓冲大小
    size_t read_buffer_size_;   // 表示实际读取缓冲大小
    size_t read_buffer_pos_;    // 表示已经使用读缓冲的大小
};

#endif // STREAMCORE_FILE_STREAM_H
